var ul = document.querySelector("ul"),
	lis = ul.getElementsByTagName("li"),
	imgs = document.querySelectorAll("img"),
	p = document.querySelectorAll("p"),
	index_arr = [0, 1, 2, 5, 8, 7, 6, 3],
	baseUrl = "http://student.0melon0.cn/index/wheel",
	path = "/get_prize_list";

ul.children[0].classList.add("active");
ajax(baseUrl + path, function(res_data) {
	var data_arr = res_data.data.prize_list;
	// console.log(data_arr);
	data_arr.forEach(function(data, index) {
		imgs[index].src = `${data.diagram}`;
		p[index].innerText = `${data.name}`;
	})
	
	var award = [];
	for(let i = 0; i < data_arr.length; i++){
		award.push(data_arr[i].name);
	}
	award.splice(3,0,"谢谢参与");
	award.splice(7,0,"谢谢参与");

	var i = 0, // 转到哪个位置
		count = 0, // 转圈初始值
		speed = 500, // 转圈速度
		totalCount = 10, // 转动的总圈数
		minSpeed = 500,
		timer = null,
		isClick = true,
		index; // 指定转到哪个奖品
		

	function roll() {
		// 速度衰减
		speed -= 50;
		if (speed <= 10) {
			speed = 10;
		}
		// 每次调用都去掉全部active类名
		for (let i = 0; i < index_arr.length; i++) {
			lis[index_arr[i]].classList.remove("active");
		}
		i++;
		// 计算转圈次数
		if(i >= index_arr.length){
			i = 0;
			count++;
		}
		lis[index_arr[i]].classList.add('active');
		// 满足转圈数和指定位置就停止
		if(count >= totalCount && i == index){
			clearTimeout(timer);
			isClick = true;
			speed = minSpeed;
			setTimeout(function(){
				alert(`${award[i]}`);
			},0)
		}else {
			timer = setTimeout(roll,speed
			);
			// 最后一圈减速
			if(count >= totalCount - 1 || speed <= 50){
				speed += 100;
			}
		}
	}
	
	ul.children[4].onclick = function(){
		if(isClick) {
			count = 0;
			index = Math.floor(Math.random()*index_arr.length)
			roll();
			isClick = false;
		}
	}
}, "get");
